package com.app.couponsharelife.ui.main.home.local

import android.content.Intent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.manager.LifecycleListener
import com.google.android.material.appbar.AppBarLayout
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.footer.LoadingView
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.LifeHomePageBean
import com.app.couponsharelife.data.bean.LifeShopPageBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.databinding.ActivityLocalShopsBinding
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.LocalShopsListAdapter
import com.app.couponsharelife.ui.adapter.ViewPagerAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.view.BannerView
import com.app.couponsharelife.ui.viewmodel.LocalViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import kotlinx.android.synthetic.main.activity_local_shops.*
import java.util.*
/**
 * 本地生活界面
 * */
class LocalShopsActivity : BaseActivity(), TencentLocationListener {

    override val viewLayoutId: Int get() = R.layout.activity_local_shops

    private var mAdapter: ViewPagerAdapter? = null

    private var mTitles = arrayListOf<String>()

    private var mPagers = arrayListOf<Fragment>()

    private var mViewModel: LocalViewModel? = null

    private var page = 1

    private var isRefresh = true

    private var isFirst = true

    /**
     * 轮播图数据
     */
    private var bannerTop: MutableList<LifeHomePageBean.BannerBean> = mutableListOf()

    private var bannerBot: MutableList<LifeHomePageBean.BannerBean> = mutableListOf()

    /**
     * 顶部轮播图监听
     */
    private var listenerTop: LifecycleListener? = null

    private var listenerBot: LifecycleListener? = null

    private var locationManager: TencentLocationManager? = null

    override fun initViews() {
        clSearchBar.setOnClickListener { startActivity(Intent(this, LocalShopsSearchActivity::class.java)) }
        clLocalAddress.setOnClickListener { startActivity(Intent(this, LocalShopsAddressSelectActivity::class.java)) }
        mMoreView.setOnClickListener {
            startActivity(Intent(this, LocalShopsListActivity::class.java))
        }
        ivBack.setOnClickListener { finish() }
        initAppBar()
        initRefreshLayout()
        initRecyclerView()
        initLocation()
    }

    private fun initLocation() {
        val request = TencentLocationRequest.create()
        request.requestLevel = TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA
        locationManager = TencentLocationManager.getInstance(this)
        val error = locationManager?.requestLocationUpdates(request, this)
        if (error != 0) {
            locationManager?.removeUpdates(this)
            println("注册失败 $error")
            AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
            AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            loadData()
        }
    }

    private fun initRefreshLayout() {
        mRefreshLayout.setTargetView(mRecyclerView)
        mRefreshLayout.setFloatRefresh(true)
        mRefreshLayout.setAutoLoadMore(true)
        mRefreshLayout.setEnableLoadmore(true)
        mRefreshLayout.setEnableOverScroll(false)
        val header = ProgressLayout(this)
        header.setColorSchemeResources(R.color.act_main_bot_nav_select_text_color)
        mRefreshLayout.setHeaderView(header)
        mRefreshLayout.setBottomView(LoadingView(this))
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = false
                loadLocalShops()
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = true
                page = 1
                loadData()
            }
        })
    }

    private fun initAppBar() {
        mAppBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            when {
                verticalOffset == 0 -> {//完全展开
                    if (mRefreshLayout != null) {
                        mRefreshLayout.setEnableRefresh(true)
                        mRefreshLayout.setEnableLoadmore(false)
                    }
                }
                Math.abs(verticalOffset) >= appBarLayout.totalScrollRange -> {//完全隐藏
                    if (mRefreshLayout != null) {
                        mRefreshLayout.setEnableRefresh(false)
                        mRefreshLayout.setEnableLoadmore(true)
                    }
                }
                else -> {//隐藏
                    if (mRefreshLayout != null) {
                        mRefreshLayout.setEnableRefresh(false)
                        mRefreshLayout.setEnableLoadmore(false)
                    }
                }
            }
        })
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.adapter = LocalShopsListAdapter(arrayListOf(), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                if (AppUtils.checkUserLogin()) {
                    val intent = Intent(this@LocalShopsActivity, LocalShopDetailActivity::class.java)
                    intent.putExtra("shopId", (arg2 as LifeShopPageBean.RecordsBean).id)
                    startActivity(intent)
                } else startActivity(Intent(this@LocalShopsActivity, NewLoginActivity::class.java))
                        //startActivity(Intent(this@LocalShopsActivity, LoginActivity::class.java))
            }
        })
    }

    private fun loadData() {
        val map = HashMap<String, String>()
        mViewModel!!.freshGetLifeHomePage(map, true)
    }

    private fun loadLocalShops() {
        val map = HashMap<String, String>()
        map["Longitude"] = AppUtils.getString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
        map["Latitude"] = AppUtils.getString("Latitude", Contacts.HZ_CENTER_LATITUDE)
        map["distance"] = "10000"
        map["pageNo"] = page.toString()
        mViewModel!!.freshGetLifeShopPage(map, true)
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(LocalViewModel::class.java)
        if (!mViewModel!!.getLifeHomePage()!!.hasObservers()) {
            mViewModel!!.getLifeHomePage()!!.observe(this, Observer {
                if (it == null) {
                    (mViewDataBinding as ActivityLocalShopsBinding).pageTipBean = parseErrorDate("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        if (isFirst)
                            (mViewDataBinding as ActivityLocalShopsBinding).pageTipBean = PageTipBean("", 0, 0)
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetLifeHomePage(hashMapOf(), false)
                        (mViewDataBinding as ActivityLocalShopsBinding).pageTipBean = parseErrorDate(it.error!!.message)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetLifeHomePage(hashMapOf(), false)
                        (mViewDataBinding as ActivityLocalShopsBinding).pageTipBean = parseErrorDate("暂无数据")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetLifeHomePage(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            (mViewDataBinding as ActivityLocalShopsBinding).pageTipBean = parseErrorDate("请求失败")
                        }
                    }
                }
            })
            mViewModel!!.getLifeShopPage()!!.observe(this, Observer {
                if (it == null) {
                    handleError("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        handleError("暂无数据")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleListContent(it.data.data!!)
                        } else {
                            handleError("请求失败")
                        }
                    }
                }
            })
        }
    }

    private fun handleError(msg: String) {
        if (page == 1 && isRefresh) {
            mRefreshLayout.finishRefreshing()
        } else
            mRefreshLayout.finishLoadmore()
        showToastMsg(msg)
    }

    private fun handleListContent(data: LifeShopPageBean) {
        if (page == 1 && isRefresh) {
            mRefreshLayout.finishRefreshing()
        } else
            mRefreshLayout.finishLoadmore()
        if (data.records.isNotEmpty()) {
            page++
            (mRecyclerView.adapter as LocalShopsListAdapter).setData(data.records, 0)
        } else {
            showToastMsg(if (page == 1) "暂无相关商家" else "暂无更多商家")
        }
    }

    private fun handleContent(data: LifeHomePageBean) {
        if (isFirst) {
            isFirst = false

            bannerTop.clear()
            bannerTop.addAll(data.topBanner)
            initBannerTop(data.bannerTop.images)

            bannerBot.clear()
            bannerBot.addAll(data.belowBanner)
            initBannerBot(data.bannerBot.images)

            initViewPager(data.classify)
        }

        (mViewDataBinding as ActivityLocalShopsBinding).pageTipBean = PageTipBean("", 0, 2)

        page = 1
        loadLocalShops()
    }

    private fun initViewPager(classify: List<LifeHomePageBean.ClassifyBean>) {

        if (classify.size <= 10) {
            mTitles.add("1")
            mPagers.add(LocalShopsTypeFragment.newInstance(
                    LifeHomePageBean.ClassifyListBean(classify)))
        } else {
            mTitles.add("1")
            mPagers.add(LocalShopsTypeFragment.newInstance(
                    LifeHomePageBean.ClassifyListBean(classify.subList(0, 10))))

            mTitles.add("2")
            mPagers.add(LocalShopsTypeFragment.newInstance(
                    LifeHomePageBean.ClassifyListBean(classify.subList(10, classify.size))))
            mIndicatorRight.visibility = View.VISIBLE
        }

        mAdapter = ViewPagerAdapter(supportFragmentManager, mPagers, mTitles)
        mTypeViewPager.adapter = mAdapter
        mTypeViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                if (position == 0) {
                    mIndicatorLeft.setBackgroundResource(R.drawable.act_local_shops_type_select_bg)
                    mIndicatorRight.setBackgroundResource(R.drawable.act_local_shops_type_no_select_bg)
                } else {
                    mIndicatorLeft.setBackgroundResource(R.drawable.act_local_shops_type_no_select_bg)
                    mIndicatorRight.setBackgroundResource(R.drawable.act_local_shops_type_select_bg)
                }
            }
        })
    }

    private fun initBannerTop(images: List<String>) {
        mBanner.start(images)
        mBanner.onStart()
        registerLifeListenerTop(mBanner)
        mBanner.onPageClickListener = object : BannerView.OnPageClickListener {
            override fun click(position: Int) {

            }
        }
    }

    private fun initBannerBot(images: List<String>) {
        mBotBanner.start(images)
        mBotBanner.onStart()
        registerLifeListenerBot(mBotBanner)
        mBotBanner.onPageClickListener = object : BannerView.OnPageClickListener {
            override fun click(position: Int) {

            }
        }
    }

    private fun registerLifeListenerTop(listener: LifecycleListener) {
        this.listenerTop = listener
        listenerTop?.onStart()
    }

    private fun registerLifeListenerBot(listener: LifecycleListener) {
        this.listenerBot = listener
        listenerBot?.onStart()
    }

    override fun onStatusUpdate(name: String?, error: Int, desc: String?) {
        if (name == "wifi" && error == 5) {
            showToastMsg("请打开GPS定位")
        }
    }

    override fun onLocationChanged(location: TencentLocation?, error: Int, reason: String?) {
        if (TencentLocation.ERROR_OK == error && location != null) {
            println(location)
            if (location.city.contains("金华")||location.city.contains("义乌")) {
                println("定位在 义乌")
                tvLocation.text=location.city
                AppUtils.setString("Longitude", location.longitude.toString())
                AppUtils.setString("Latitude", location.latitude.toString())
            } else {
                println("定位不在 义乌")
                tvLocation.text="杭州"
                AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
                AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            }
        } else {
            println("定位失败 $error")
            AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
            AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
        }
        locationManager?.removeUpdates(this)
        loadData()
    }
}
